// 加载所需的模块
const fs = require("fs");
const path = require("path");
const express = require("express");
const cors = require("cors");

// 创建app
const app = express();

app.listen(3000, () => console.log("server start"));

// 中间件
app.use(express.urlencoded({ extended: false }));

app.use(cors());

// 得到book.json的路径
const bookPath = path.join(__dirname, "book.json");
// 接口
app.get("/api/getbooks", (req, res) => {
    fs.readFile(bookPath, "utf-8", (err, data) => {
        if (err) return console.log(err);
        res.send({
            status: 200,
            msg: "获取成功",
            data: JSON.parse(data),
        });
    });
});

app.post("/api/addbook", (req, res) => {
    req.body.id = Date.now();
    fs.readFile(bookPath, "utf-8", (err, data) => {
        // console.log(data);
        if (err) return console.log(err);
        data = JSON.parse(data);
        // console.log(data);
        data.push(req.body);
        fs.writeFile(bookPath, JSON.stringify(data), (err) => {
            if (err) {
                res.send({ status: 400, msg: "添加失败" });
            } else {
                console.log(data);
                res.send({ status: 201, mag: "添加成功" });
            }
        });
    });
});

app.get("/api/delbook", (req, res) => {
    let id = req.query.id;
    fs.readFile(bookPath, "utf-8", (err, data) => {
        if (err) return console.log("读取失败");
        data = JSON.parse(data);
        console.log(data);
        let result = data.filter((item) => item.id != id);
        // console.log(JSON.stringify(result) == JSON.stringify(data));
        if (JSON.stringify(result) == JSON.stringify(data)) {
            res.send({ status: 400, msg: "输入的id有误" });
        }
        fs.writeFile(bookPath, JSON.stringify(result), (err) => {
            if (err) {
                console.log(err);
                res.send({ status: 400, msg: "删除失败" });
            } else {
                res.send({ status: 201, msg: "删除成功" });
            }
        });
    });
});